/**
 * header数据列表的分页组件
 */
let headerPageComponent;

/**
 * 用于存放template item列表的分页组件的map,
 * key 的格式为 templateId_{templateId}
 */
let pageComponentMap = {
};

/**
 * 状态map
 */
let typeMap = {
    "1": "TEXT",
    "2": "FILE"
}

/**
 * 为添加template的panel增加校验逻辑
 *
 * @param editTemplatePanel 添加template panel
 */
function addValidatorForEditPanel(editTemplatePanel) {
    editTemplatePanel.bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            code: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The code is required'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9\-\\.]+$/,
                        message: "Only characters, numbers, \"-\" or \".\" are allowed"
                    },
                    remote: {
                        type: 'GET',
                        headers: {
                            Authorization: JwtTokenUtils.getBearerHeader()
                        },
                        message: "No. already exists, please replace with a new one",
                        url: "/service/datacenter/template/checkTemplateCodeExists",
                        delay: 1000
                    }
                }
            },
            type: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The type is required'
                    }
                }
            },
            name: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The name is required'
                    }
                }
            },
            content: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The content is required'
                    }
                }
            }
        }
    });

    let type = editTemplatePanel.find(".type-value:checked").val();
    extendValidatorForEditPanel(type, editTemplatePanel);

    editTemplatePanel.find(".type-element .type-value").change(function () {
        let type = editTemplatePanel.find(".type-value:checked").val();
        extendValidatorForEditPanel(type, editTemplatePanel);
    });
}

/**
 * 根据模板类型进行扩展校验
 * 
 * @param {*} type 模板类型
 */
function extendValidatorForEditPanel(type, editTemplatePanel) {
    var validator = editTemplatePanel.data('bootstrapValidator');
    if (type == 1) {
        validator.enableFieldValidators('content', true);
        validator.options.fields.content = {
            group: '.input-div',
            validators: {
                notEmpty: {
                    message: 'The content is required'
                }
            }
        }
        editTemplatePanel.find(".content-label").addClass("required");
    }
    else {
        validator.enableFieldValidators('content', false);
        editTemplatePanel.find(".content-label").removeClass("required");
    }
    validator.validateField("content");
}

/**
 * 添加Message
 * @param addTemplatePanel message添加面板
 */
function addTemplate(addTemplatePanel) {
    let requestData = {};
    requestData.code = addTemplatePanel.find(".code-value").val();
    requestData.type = addTemplatePanel.find(".type-value:checked").val();
    requestData.name = addTemplatePanel.find(".name-value").val();
    requestData.description = addTemplatePanel.find(".description-value").val();
    requestData.content = addTemplatePanel.find(".content-value").val();
    requestData.fileStoreName = addTemplatePanel.find(".file-name").attr("file-store-name");

    $.ajax({
        type: 'POST',
        url: "/service/datacenter/template/addTemplate",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            addTemplatePanel.remove();
            $(".component .add-new-panel").removeClass("disable");
            $(".component .app-list").empty();
            headerPageComponent.query();
        }
    });
}

/**
 * 修改template
 *
 * @param updateDataPanel 修改面板
 */
function updateTemplate(updateDataPanel) {
    let requestData = {};
    requestData.id = updateDataPanel.attr("id");
    requestData.name = updateDataPanel.find(".name-value").val();
    requestData.description = updateDataPanel.find(".description-value").val();
    requestData.content = updateDataPanel.find(".content-value").val();
    requestData.fileStoreName = updateDataPanel.find(".template-file .file-name").attr("file-store-name");

    $.ajax({
        type: 'PUT',
        url: "/service/datacenter/template/updateTemplate",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            headerPageComponent.refreshData();
        }
    });
}

/**
 * 查询template列表
 *
 * @param pageComponent 分页组件
 */
function queryTemplates(pageComponent) {
    let requestData = {
        pageSize: pageComponent.size,
        pageNumber: pageComponent.number,
        query: pageComponent.queryParam
    };
    $.ajax({
        type: 'POST',
        url: "/service/datacenter/template/page/queryTemplates",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function (data) {
            $(".component .data-list").empty();

            let pageParams = {};
            pageParams.totalPages = data.totalPages;
            pageParams.number = data.number;
            pageParams.size = data.size;

            pageComponent.rebuildHtmlDom(pageParams);

            let content = data.content;

            for (let i = 0; i < content.length; i++) {
                let template = content[i];
                let templatePanel = $(".component .templates .data-panel").clone();
                templatePanel.find(".panel-title").text(template.name);
                templatePanel.attr("id", template.id);
                templatePanel.css("display", "block");
                templatePanel.find(".id-value").text(template.id);
                templatePanel.find(".code-value").text(template.code);
                let type = template.type;
                templatePanel.find(".type-value").text(typeMap[type]);
                templatePanel.find(".name-value").text(template.name);
                templatePanel.find(".description-value").text(template.description);
                if (type == 1) {
                    templatePanel.find(".content-element").show();
                    templatePanel.find(".template-file").hide();
                }
                else {
                    templatePanel.find(".content-element").hide();
                    templatePanel.find(".template-file").show();
                }
                templatePanel.find(".content-value").text(template.content);
                templatePanel.find(".template-file").attr("fileStoreName", template.fileStoreName);
                templatePanel.find(".template-file-value").text(template.fileName);

                templatePanel.find(".template-file-value").click(function () {
                    let url = "/service/datacenter/template/downloadTemplateFile/" + template.fileStoreName;
                    IntegrationUtils.downloadFile(url, "GET");
                });

                templatePanel.find(".edit-button").click(function () {
                    let editTemplatePanel = $(".component .templates .edit-data-panel").clone();
                    editTemplatePanel.attr("id", template.id);
                    editTemplatePanel.find(".panel-title").text("Modify Template");
                    editTemplatePanel.find(".code-value").val(template.code);
                    editTemplatePanel.find(".code-value").attr("disabled", "disabled");
                    editTemplatePanel.find(".code-label").removeClass("required");
                    editTemplatePanel.find(".type-value[value=" + template.type + "]").prop("checked", "true");
                    editTemplatePanel.find(".type-value").attr("disabled", "disabled");
                    editTemplatePanel.find(".type-value").removeClass("required");
                    editTemplatePanel.find(".name-value").val(template.name);
                    editTemplatePanel.find(".description-value").text(template.description);
                    editTemplatePanel.find(".content-value").text(template.content);
                    if (template.type == "2") {
                        editTemplatePanel.find(".file-display").addClass("show");
                        editTemplatePanel.find(".content-element").hide();
                    }
                    else {
                        editTemplatePanel.find(".template-file").hide();
                    }
                    editTemplatePanel.find(".file-display .file-name").text(template.fileName);
                    editTemplatePanel.find(".file-display .file-name").attr("file-store-name", template.fileStoreName);

                    editTemplatePanel.find(".file-display .file-name").click(function () {
                        let url = "/service/datacenter/template/downloadTemplateFile/" + template.fileStoreName;
                        IntegrationUtils.downloadFile(url, "GET");
                    });

                    editTemplatePanel.find(".save-button").click(function () {
                        editTemplatePanel.bootstrapValidator('validate');
                        let invalidFields = editTemplatePanel.data('bootstrapValidator').getInvalidFields();
                        if (invalidFields.length === 0) {
                            let type = editTemplatePanel.find(".type-value:checked").val();
                            let fileStoreName = editTemplatePanel.find(".template-file .file-name").attr("file-store-name");
                            if(type == 2 && !fileStoreName) {
                                let invalidMessage = editTemplatePanel.find(".template-file .invalid-message");
                                invalidMessage.text("Template file is required,please upload.");
                                invalidMessage.addClass("show");
                                return;
                            }
                            else {
                                updateTemplate(editTemplatePanel);
                            }
                        }
                    });

                    editTemplatePanel.find(".upload-button").click(function () {
                        editTemplatePanel.find(".upload-input").click();
                    });

                    editTemplatePanel.find(".upload-input").on("change", function (event) {
                        var files = event.target.files;
                        if (files.length > 0) {
                            var file = files[0];
                            var formData = new FormData();
                            formData.append('file', file);
                            $.ajax({
                                url: "/service/datacenter/template/uploadTemplateFile",
                                type: 'POST',
                                data: formData,
                                processData: false,
                                contentType: false,
                                headers: {
                                    Authorization: JwtTokenUtils.getBearerHeader()
                                },
                                success: function (responseData) {
                                    editTemplatePanel.find("file-display").addClass("show");
                                    editTemplatePanel.find(".file-name").attr("file-store-name", responseData.data);
                                    editTemplatePanel.find(".file-name").text(file.name);
                                    editTemplatePanel.find(".invalid-message").removeClass("show");
                                }
                            });
                        }
                    });

                    editTemplatePanel.find(".delete-file-button").click(function () {
                        editTemplatePanel.find(".file-display").removeClass("show");
                        editTemplatePanel.find(".file-name").removeAttr("file-store-name");
                        editTemplatePanel.find(".file-name").text("");
                    });

                    editTemplatePanel.find(".cancel-button").click(function () {
                        editTemplatePanel.remove();
                        templatePanel.css("display", "block");
                    });

                    editTemplatePanel.insertBefore($(this).parents(".data-panel"));

                    addValidatorForEditPanel(editTemplatePanel);

                    templatePanel.css("display", "none");
                });

                templatePanel.find(".delete-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure to delete this template?", function () {
                        $.ajax({
                            type: 'DELETE',
                            url: "/service/datacenter/template/deleteTemplate/" + template.id,
                            contentType: "application/json;charset=UTF-8",
                            headers: {
                                Authorization: JwtTokenUtils.getBearerHeader()
                            },
                            success: function () {
                                pageComponent.refreshData();
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                $(".component .data-list").append(templatePanel);
            }
        }
    });
}

/**
 * 添加按钮点击事件处理
 * 添加新微服务div显示
 */
function addNewHandle() {
    if ($(".component .add-new-panel").hasClass("disable")) {
        return;
    }

    let addPanel = $(".component .templates .edit-data-panel").clone();

    addPanel.find(".type-element .type-value[value=1]").prop("checked", true);

    addPanel.css("margin-bottom", "0");
    addPanel.find(".panel-title").text("Add Template");
    addPanel.find(".save-button").click(function () {
        addPanel.bootstrapValidator('validate');
        let invalidFields = addPanel.data('bootstrapValidator').getInvalidFields();
        if (invalidFields.length == 0) {
            let type = addPanel.find(".type-value:checked").val();
            let fileStoreName = addPanel.find(".template-file .file-name").attr("file-store-name");
            if(type == 2 && !fileStoreName) {
                let invalidMessage = addPanel.find(".template-file .invalid-message");
                invalidMessage.text("Template file is required,please upload.");
                invalidMessage.addClass("show");
                return;
            }
            else {
                addTemplate(addPanel);
            }
        }
    });

    addPanel.find(".cancel-button").click(function () {
        addPanel.remove();
        $(".component .add-new-panel").removeClass("disable");
    });

    addPanel.find(".upload-button").click(function () {
        addPanel.find(".upload-input").click();
    });

    addPanel.find(".upload-input").on("change", function (event) {
        var files = event.target.files;
        if (files.length > 0) {
            var file = files[0];
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: "/service/datacenter/template/uploadTemplateFile",
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    Authorization: JwtTokenUtils.getBearerHeader()
                },
                success: function (responseData) {
                    addPanel.find(".file-display").addClass("show");
                    addPanel.find(".file-name").attr("file-store-name", responseData.data);
                    addPanel.find(".file-name").text(file.name);
                    addPanel.find(".invalid-message").removeClass("show");
                }
            });
        }
    });

    addPanel.find(".delete-file-button").click(function () {
        addPanel.find(".file-display").removeClass("show");
        addPanel.find(".file-name").removeAttr("file-store-name");
        addPanel.find(".file-name").text("");
    });

    addValidatorForEditPanel(addPanel);

    $(".component .add-div").append(addPanel);
    $(".component .add-new-panel").addClass("disable");
}

/**
 * 页面启动完成事件
 *
 */
$(document).ready(function () {
    headerPageComponent = PageComponentUtils.createPageComponent({
        size: 10,
        number: 0,
        container: $(".component .data-div"),
        queryParam: "",
        doQuery: (pg) => {
            queryTemplates(pg);
        }
    });
    headerPageComponent.query();


    $(".component .query-div .operation-div .query-button").click(function () {
        let queryParam = $(".component .query-div .query-input").val();
        headerPageComponent.query(queryParam);
    });

    $(".component .query-div .query-form .query-input").keydown(function (e) {
        if (e.keyCode === 13) {
            let queryParam = $(".component .query-div .query-input").val();
            headerPageComponent.query(queryParam);
        }
    });
});
